package com.example.guiguihomemedical.service.impl;

import com.example.guiguihomemedical.common.FileUploadResult;
import com.example.guiguihomemedical.entity.Examination;
import com.example.guiguihomemedical.entity.ExaminationTable;
import com.example.guiguihomemedical.entity.Record;
import com.example.guiguihomemedical.entity.Signing;
import com.example.guiguihomemedical.entity.dto.*;
import com.example.guiguihomemedical.mapper.ExaminationMapper;
import com.example.guiguihomemedical.service.ExaminaionService;
import com.example.guiguihomemedical.service.FileUploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ExaminationServiceImpl implements ExaminaionService {
    @Autowired
    private FileUploadService fileUploadService;
    @Autowired
    private ExaminationMapper examinationMapper;

    @Override
    public void addExaminaion(ExaminationAdd examinationAdd, MultipartFile uploadFile) {
        long currentTimeMillis = System.currentTimeMillis();
        Date currentDate = new Date(currentTimeMillis);
        Examination examination = new Examination();
        FileUploadResult fileUploadResult = fileUploadService.upload(uploadFile);
        examination.setElectrocardiogram(fileUploadResult.getImgurl());
        examination.setIdcard(examinationAdd.getIdcard());
        examination.setId(examinationAdd.getId());
        examination.setPulseRate(examinationAdd.getPulseRate());
        examination.setRespiratoryRate(examinationAdd.getRespiratoryRate());
        examination.setLeftPressure(examinationAdd.getLeftPressure());
        examination.setRightPressure(examinationAdd.getRightPressure());
        examination.setWeight(examinationAdd.getWeight());
        examination.setWaist(examinationAdd.getWaist());
        examination.setMbi(examinationAdd.getMbi());
        examination.setOldHealthy(examinationAdd.getOldHealthy());
        examination.setOldSelfCare(examinationAdd.getOldSelfCare());
        examination.setOldCognition(examinationAdd.getOldCognition());
        examination.setOldEmotion(examinationAdd.getOldEmotion());
        examination.setDiet(examinationAdd.getDiet());
        examination.setExercise(examinationAdd.getExercise());
        examination.setSleep(examinationAdd.getSleep());
        examination.setDrink(examinationAdd.getDrink());
        examination.setWork(examinationAdd.getWork());
        examination.setLip(examinationAdd.getLip());
        examination.setDentalCaries(examinationAdd.getDentalCaries());
        examination.setPharynx(examinationAdd.getPharynx());
        examination.setLeftEye(examinationAdd.getLeftEye());
        examination.setRightEye(examinationAdd.getRightEye());
        examination.setHearing(examinationAdd.getHearing());
        examination.setMotion(examinationAdd.getMotion());
        examination.setFundus(examinationAdd.getFundus());
        examination.setSkin(examinationAdd.getSkin());
        examination.setUrineProtein(examinationAdd.getUrineProtein());
        examination.setUrinarySugar(examinationAdd.getUrinarySugar());
        examination.setUrinaryKetoneBody(examinationAdd.getUrinaryKetoneBody());
        examination.setUrinaryOccultBlood(examinationAdd.getUrinaryOccultBlood());
        examination.setUrinaryOther(examinationAdd.getUrinaryOther());
        examination.setFastingBloodGlucose(examinationAdd.getFastingBloodGlucose());
        examination.setDiagnosticResults(examinationAdd.getDiagnosticResults());
        examination.setMicroUrineProtein(examinationAdd.getMicroUrineProtein());
        examination.setFecalOccultBlood(examinationAdd.getFecalOccultBlood());
        examination.setGlycosylatedHemoglobin(examinationAdd.getGlycosylatedHemoglobin());
        examination.setHbsag(examinationAdd.getHbsag());
        examination.setSerumAlanineAminotransferase(examinationAdd.getSerumAlanineAminotransferase());
        examination.setSerumAspartateAminotransferase(examinationAdd.getSerumAspartateAminotransferase());
        examination.setAlbumin(examinationAdd.getAlbumin());
        examination.setTotalBilirubin(examinationAdd.getTotalBilirubin());
        examination.setSymptom(examinationAdd.getSymptom());
        examination.setTemperature(examinationAdd.getTemperature());
        examination.setStarttime(currentDate);
        examination.setHeight(examinationAdd.getHeight());
        examination.setKongfuxuetang(examinationAdd.getKongfuxuetang());
        examinationMapper.insertExamination(examination);
    }

    @Override
    public void postExaminationTable(ExaminationTableAdd examinationTableAdd, MultipartFile uploadFile) {
        Integer examinationid = examinationTableAdd.getExaminationid();
        ExaminationTable examinationTable = new ExaminationTable();
        FileUploadResult fileUploadResult = fileUploadService.upload(uploadFile);
        examinationTable.setExaminationtable(fileUploadResult.getImgurl());
        examinationTable.setExaminationid(examinationid);
        log.info("要插入的数据：" + examinationTable);
        ExaminationTable examinationTable1 = examinationMapper.getExaminationTable(examinationid);
        if (examinationTable1 == null) {
            examinationMapper.insertTable(examinationTable);
        } else {
            examinationMapper.updateTable(examinationTable);
        }
    }

    @Override
    public List<ExaminationSigning> getExaminationSigningList() {
        List<ExaminationSigning> examinationSignings = new ArrayList<>();
        List<Record> records = examinationMapper.getExaminationSigningList();
        for (Record record : records) {
            String idcard = record.getIdcard();
            String birthdayString = idcard.substring(6, 14);
            LocalDate birthday = LocalDate.parse(birthdayString, DateTimeFormatter.ofPattern("yyyyMMdd"));
            Integer age = calculateAge(birthday, LocalDate.now());

            List<String> listenerNames = examinationMapper.getListenerNamesById(record.getIdcard());
            ExaminationSigning examinationSigning = new ExaminationSigning(
                    record.getIdcard(),
                    record.getName(),
                    record.getSex(),
                    age,
                    listenerNames
            );
            examinationSignings.add(examinationSigning);
        }
        return examinationSignings;
    }

    @Override
    public List<ExaminationSigning> getExaminationSigningSearch(String idcardname) {
        List<ExaminationSigning> examinationSigningList = getExaminationSigningList();
        List<ExaminationSigning> currentExamaintionSigningList = new ArrayList<>();
        for (ExaminationSigning examinationSigning : examinationSigningList) {
            if (matchesSearchESigning(examinationSigning, idcardname)) {
                currentExamaintionSigningList.add(examinationSigning);
            }
        }
        log.info(currentExamaintionSigningList.toString());
        return currentExamaintionSigningList;
    }

    @Override
    public Examination getExaminationDetailByIdcard(Integer examinationId) {
        return examinationMapper.getExaminationDetailByIdcard(examinationId);
    }

    @Override
    public List<ExaminationRecord> getExaminationRecordList(ExaminationRecordSearch examinationRecordSearch) {
        List<ExaminationRecord> examinationRecords = getExaminationRecordList();
        log.info("体检列表未处理" + examinationRecords.toString());
        log.info("体检查询条件" + examinationRecordSearch.toString());
        if (examinationRecordSearch.getIdcardname() == "-1" && examinationRecordSearch.getListenername().isEmpty() && examinationRecordSearch.getStarttime() == -1) {
            return examinationRecords;
        }
        List<ExaminationRecord> currentExamaintionRecordList = new ArrayList<>();
        for (ExaminationRecord examinationRecord : examinationRecords) {
            if (matchesSearchERecord(examinationRecord, examinationRecordSearch)) {
                currentExamaintionRecordList.add(examinationRecord);
            }
        }
        log.info(currentExamaintionRecordList.toString());

        return currentExamaintionRecordList;

    }

    @Override
    public void modifyExaminationById(Examination examination) {
        examinationMapper.modifyExaminationById(examination);
    }

    @Override
    public String GetAddStatus(String idcard) {
        List<Signing> signings = examinationMapper.getAddStatus(idcard);
        return (signings.isEmpty()) ? "0" : "1";
    }


    private boolean matchesSearchESigning(ExaminationSigning examinationSigning, String idcardname) {
        if (examinationSigning.getIdcard().contains(idcardname) || examinationSigning.getName().contains(idcardname)) {
            return true;
        }
        return false;
    }

    private Integer calculateAge(LocalDate birthday, LocalDate currentday) {
        int age = currentday.getYear() - birthday.getYear();
        if (currentday.getMonthValue() < birthday.getMonthValue() || currentday.getMonthValue() == currentday.getMonthValue() && currentday.getDayOfMonth() < birthday.getDayOfMonth()) {
            age--;
        }
        return age;
    }

    private Boolean matchesSearchERecord(ExaminationRecord examinationRecord,
                                         ExaminationRecordSearch examinationRecordSearch) {
        Calendar calendar = Calendar.getInstance();
        // 获取三个月前的时间
        calendar.add(Calendar.MONTH, -3);
        Date threeMonthsAgo = calendar.getTime();
        // 获取半年前的时间
        calendar.add(Calendar.MONTH, -3); // 再减去3个月
        Date sixMonthsAgo = calendar.getTime();
        // 获取一年前的时间
        calendar.add(Calendar.MONTH, -6); // 再减去6个月
        Date oneYearAgo = calendar.getTime();
        Date searchtime = new Date();
        Integer intSearchtime = examinationRecordSearch.getStarttime();
        switch (intSearchtime) {
            case 0:
                searchtime = threeMonthsAgo;
                break;
            case 1:
                searchtime = sixMonthsAgo;
                break;
            case 2:
                searchtime = oneYearAgo;
                break;
            case -1:
                break;
        }
        int result = searchtime.compareTo(examinationRecord.getStarttime());
        if (examinationRecordSearch.getStarttime() != -1 && result > 0) {
            return false;
        }
        if (!(examinationRecord.getIdcard().contains(examinationRecordSearch.getIdcardname()) ||
                examinationRecord.getName().contains(examinationRecordSearch.getIdcardname())) &&
                !examinationRecordSearch.getIdcardname().equals("-1")) {
            log.info("idcardname不等");
            return false;
        }
        if (examinationRecordSearch.getListenername() != null && !examinationRecord.getListenername().containsAll(examinationRecordSearch.getListenername())) {
            log.info("人群种类不等");
            return false;
        }
        return true;
    }

    private List<ExaminationRecord> getExaminationRecordList() {
        List<ExaminationRecord> examinationRecords = new ArrayList<>();
        List<ExaminationRecord> examinationRecords1 = examinationMapper.getExaminationRecordList();
        for (ExaminationRecord examinationRecord : examinationRecords1) {
            String idcard = examinationRecord.getIdcard();
            String birthdayString = idcard.substring(6, 14);
            LocalDate birthday = LocalDate.parse(birthdayString, DateTimeFormatter.ofPattern("yyyyMMdd"));
            Integer age = calculateAge(birthday, LocalDate.now());

            List<String> listenerNames = examinationMapper.getListenerNamesById(examinationRecord.getIdcard());
            ExaminationRecord examinationRecord1 = new ExaminationRecord(
                    examinationRecord.getExaminationid(),
                    examinationRecord.getIdcard(),
                    examinationRecord.getName(),
                    examinationRecord.getSex(),
                    age,
                    examinationRecord.getStarttime(),
                    listenerNames
            );
            examinationRecords.add(examinationRecord1);
        }
        return examinationRecords;
    }
}
